package com.cdinternationalcompany.syhapp.push.hw

import android.util.Log
import com.cdinternationalcompany.syhapp.push.Constants.Companion.tag
import com.cdinternationalcompany.syhapp.push.NotificationHelper
import com.cdinternationalcompany.syhapp.push.TokenObserver
import com.cdinternationalcompany.syhapp.utils.ChannelManager
import com.google.gson.Gson
import com.huawei.hms.common.internal.HmsClient
import com.huawei.hms.push.HmsMessageService
import com.huawei.hms.push.RemoteMessage
import org.json.JSONObject
import java.lang.Exception

class HMSPushService : HmsMessageService() {

    companion object {
        private val TAG = "$tag.${HMSPushService::class.java.simpleName}"
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, " HMSPushService#onCreate -> ")
    }

    override fun onMessageReceived(msg: RemoteMessage?) {
        super.onMessageReceived(msg)
        Log.d(TAG, " HMSPushService#onMessageReceived ->  ${Gson().toJson(msg)}")
        try {
            val json = JSONObject(msg?.data)
            Log.d(TAG, "HMSPushService#json ->  $json")
            NotificationHelper.showNotification(
                application,
                json.getString("title"),
                json.getString("content"),
                JSONObject().apply {
                    put("url", json.getString("url"))
                }.toString()
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }




    override fun onNewToken(token: String?) {
        super.onNewToken(token)
        if (token != null) {
            val para = mapOf<String,String>(Pair("token",token),Pair("platform","1"))
            ChannelManager.instance.callFlutter("PushApi/registerId", para)
        }
    }

}